/* eslint-disable react/jsx-props-no-spreading */
import { Widget } from '@web/com/models/appConfig';
import { WidgetLayoutProps, WidgetsContainerInfo } from '@web/com/models/widgetModel';
import React, { lazy, MouseEvent } from 'react';
import { widgetPool } from '../configManager/configLoader';

const widgetOnClick = (e:MouseEvent, widgetInfo:Widget):void => {
  console.log('menuClick', e);
  console.log('widgetInfo', widgetInfo);
};

const loadWidgetConainers = ():WidgetsContainerInfo[] => {
  const { widgets, layouts } = widgetPool;
  const layoutWidgets = {};
  widgets.forEach((widget) => {
    const newWidget = widget as unknown as Widget;
    if (layoutWidgets[widget.layout]) {
      layoutWidgets[widget.layout].widgets.push(newWidget);
    } else {
      const wigetLayout:WidgetLayoutProps = {
        widgets: [newWidget],
        menuClickCallBack: widgetOnClick,
      };
      layoutWidgets[widget.layout] = wigetLayout;
    }
  });

  const widgetContainers:WidgetsContainerInfo[] = [];
  layouts.forEach((widgetLayout) => {
    const { name, path, position } = widgetLayout;
    if (position) {
      Object.keys(position).forEach((key) => {
        position[key] = position[key].toString().indexOf('px') > -1 ? position[key] : `${position[key]}px`;
      });
    }
    if (layoutWidgets[name]) {
      layoutWidgets[name].position = position;
      const WidgetContainerElement = lazy(() => import(`@layout/MapWdtLayouts/barLayouts/${path}`));
      const widgetConInfo = {
        id: widgetLayout.id,
        widgetsContainer: WidgetContainerElement,
        wProps: layoutWidgets[name],
      };
      widgetContainers.push(widgetConInfo);
    }
  });

  return widgetContainers;
};

const WidgetManager = ():JSX.Element => {
  const widgetContainers = loadWidgetConainers();
  return (
    <>
      {
        widgetContainers.map((conLayoutInfo) => {
          const WidgetLayout = conLayoutInfo.widgetsContainer;
          return (
            <WidgetLayout key={conLayoutInfo.id} {...conLayoutInfo.wProps} />
          );
        })
      }
    </>
  );
};

export default WidgetManager;
